package com.example.demo.nyxcosmetics;

import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageDownload {
    private String imageUrl = "https://www.nyxcosmetics.com/dw/image/v2/AANG_PRD/on/demandware.static/-/Sites-cpd-nyxusa-master-catalog/default/dw6958001d/ProductImages/2018/Lips/Lip_Lingerie_Gloss/800897155254_liplingeriegloss_clear_main.jpg";
    private String filePath = "C:\\Users\\blysin\\Documents\\workspaces\\java\\demo\\src\\test\\java\\com\\example\\demo\\nyxcosmetics\\export.jpg";
    private String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"; // 示例用户代理


    @Test
    @SneakyThrows
    public void download() {
        OkHttpClient client = new OkHttpClient.Builder()
                .build();

        Request request = new Request.Builder()
                .url(imageUrl)
                .addHeader("User-Agent", userAgent) // 设置用户代理
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 读取响应体
            InputStream inputStream = response.body().byteStream();
            File file = new File(filePath);

            // 将图片写入文件
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            System.out.println("Image downloaded successfully: " + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
